package com.espressif.iot.ui.device.dialog;



import java.net.InetAddress;

import com.espressif.iot.device.IEspDevice;
import com.espressif.iot.device.builder.BEspDevice;
import com.espressif.iot.device.cache.IEspDeviceCache.NotifyType;
import com.espressif.iot.model.device.EspDevice;
import com.espressif.iot.model.device.EspDeviceGateway;
import com.espressif.iot.model.device.cache.EspDeviceCache;
import com.espressif.iot.type.device.EspDeviceType;
import com.espressif.iot.type.device.IEspDeviceStatus;
import com.espressif.iot.type.device.state.EspDeviceState;
import com.espressif.iot.type.device.status.EspStatusPlug;
import com.espressif.iot.type.device.status.IEspStatusPlug;
import com.espressif.iot.user.IEspUser;
import com.espressif.iot.user.builder.BEspUser;
import com.google.zxing.qrcode.ui.ShareCaptureActivity;
import com.lishate.update.GatewayItem;
import com.mob.tools.utils.HEX;
import com.xiquezhijia.iot.R;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

public  class XqaddchilddeviceDialog implements DialogInterface,  android.view.View.OnClickListener, 
						DialogInterface.OnClickListener, DialogInterface.OnDismissListener, DialogInterface.OnCancelListener
{
   
    
    protected AlertDialog mDialog;
    protected Context mContext;
    protected CheckBox  test_onoff;
    
    private EditText  devicename;
    private Spinner   inroom;
    private Spinner   belonghost;
    
    private EspDeviceType devicetype;
    private String  devicekey;
    
    private String ZigBeeMac; 
    
    private EspDeviceGateway belonggaway;
    
    private static IEspDevice xq_device=null;
    private EspDeviceType deviceType;
    private long  devid;
    private int serial;
    private long zoneid;
    
    public XqaddchilddeviceDialog(Context context, EspDeviceType type, String keyid)
    {
        mContext = context;
        devicekey = keyid;
        devicetype = type;
    }
    
    //覆写父类的方法
    /* 这是DialogInterface类的抽象方法
     * 供外部调用的，供实例化对象调用的
     * 
     * */
    @Override
    public void cancel()
    {
        if (mDialog != null)
        {
            mDialog.cancel();
        }
    }
    
    //覆写父类的方法
    //供外部调用的，供实例化对象调用的
    @Override
    public void dismiss()
    {
        if (mDialog != null)
        {
            mDialog.dismiss();
        }
    }

    //覆写父类的方法
    //@Override
    public void show()
    {

        
        LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View layout = inflater.inflate(R.layout.xqaddchilddialog,
		                               null);
		devicename = (EditText)layout.findViewById(R.id.devname);
		inroom = (Spinner)layout.findViewById(R.id.selectroom);
		belonghost = (Spinner)layout.findViewById(R.id.selecthost);
		test_onoff = (CheckBox)layout.findViewById(R.id.testdevice);
		test_onoff.setOnClickListener(this);
		
		//进行把设备的Mac地址解析出来
		ZigBeeMac = devicekey.substring(0, 16);
		
		deviceType = EspDeviceType.getDevicetypte(devicekey);
      	serial = deviceType.getSerial();
      	byte[] hexdat = HEX.decodeHexString((devicekey.substring(6, 16)));
      	devid = ((long)hexdat[0]<<32) + ((long)hexdat[1]<<24) + ((long)hexdat[2]<<16) +
      			((long)hexdat[3]<<8) + ((long)hexdat[4]);
		
        mDialog =
            new AlertDialog.Builder(mContext)
                .setView(layout)
                .setNegativeButton(R.string.no,this)
                .setCancelable(true)
                .show();
        mDialog.setOnDismissListener(this);
        mDialog.setCanceledOnTouchOutside(false);
        mDialog.setOnCancelListener(this);
        
        
        
    }
    
    private class GetDeviceAsyncTask extends AsyncTask<Boolean, Object, Boolean>
    {
        
        private ProgressDialog mProgressDialog;
        private IEspDevice espXqdev;
        private IEspDeviceStatus devstatus;
        public GetDeviceAsyncTask(IEspDevice xq_device, IEspDeviceStatus status) {
			// TODO Auto-generated constructor stub
        	espXqdev = xq_device;
        	devstatus  = status;
		}

		@Override
        protected void onPreExecute()
        {
            mProgressDialog = new ProgressDialog((ShareCaptureActivity)mContext);
            mProgressDialog.setMessage(mContext.getString(R.string.esp_qrcode_capturing_message));
            mProgressDialog.setCanceledOnTouchOutside(false);
            mProgressDialog.show();
        }
        
        @Override
        protected Boolean doInBackground(Boolean... params)
        {
            //String shareKey = params[0];
            //Log.debug("shareKey is : " + shareKey);
            IEspUser user = BEspUser.getBuilder().getInstance();
            return user.doActionPostDeviceStatus(espXqdev, devstatus);
        }
        
        @Override
        protected void onPostExecute(Boolean result)
        {
            mProgressDialog.dismiss();
            mProgressDialog = null;
            Activity activity = (ShareCaptureActivity)mContext;
            int toastMsg;
            if (result)
            {
                toastMsg = R.string.esp_qrcode_capture_result_success;
            }
            else
            {
                toastMsg = R.string.esp_qrcode_capture_result_failed;
                espXqdev.setDeviceState(EspDeviceState.OFFLINE);
            }
            Toast.makeText(activity, toastMsg, Toast.LENGTH_LONG).show();
            EspDeviceCache.getInstance().addSharedDeviceCache(espXqdev);
            //广播一个命令去读取配置成功的设备，然后显示在界面上
            EspDeviceCache.getInstance().notifyIUser(NotifyType.STATE_MACHINE_UI);
            
//            espXqdev.saveInDB();
            
            
            if(result == true)
            //退出扫描二维码界面
            	activity.finish();
        }
        
    }

	@Override
	public void onClick(DialogInterface dialog, int which) {
		// TODO Auto-generated method stub
		dialog.cancel();
		adddevicelistener.IsSucAdddevice(false);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		
		if(v == test_onoff){
			//进行发数据进行测试
			if(xq_device == null){
				xq_device =  
						BEspDevice.getInstance().alloc(null, devid, devicekey, false, ZigBeeMac, 
								0, serial, null, null, -1, zoneid);
				
			}
			SetEspDeviceStatus(xq_device, test_onoff.isChecked());
			
		}
	
	}

	private void SetEspDeviceStatus(IEspDevice xq_device2, boolean checked) {
		// TODO Auto-generated method stub
		IEspDeviceStatus status = null;
		switch(xq_device2.getDeviceType()){
		case PLUG_XQ:
			status = new EspStatusPlug();
            ((IEspStatusPlug)status).setIsOn(checked);
			 break;
		default :
			
			return;
		}
		xq_device.setDeviceState(EspDeviceState.LOCAL);
		xq_device.setGateWay(belonggaway);
		new GetDeviceAsyncTask(xq_device, status).execute();
	}

	//对话窗口取消的过程中，移除所有任务
    /* public static interface DialogInterface.OnCancelListener 
     * 里面的抽象方法
     * The dialog that was canceled will be passed into themethod.
     * 继承了DialogInterface.OnCancelListener就要选择性实现他的抽象方法
     * */
    @Override
    public void onCancel(DialogInterface dialog)
    {
    		
    }
    
    //撤销该任务
    /* public static interface DialogInterface.OnDismissListener 
     * 里面的抽象方法
     *  The dialog that was dismissed will be passed into themethod.
     *  继承了DialogInterface.OnDismissListener就要选择性实现他的抽象方法
     * */
    @Override
    public void onDismiss(DialogInterface dialog)
    {
       
    }
    
   
    public interface OnAddDeviceListener
    {
        void IsSucAdddevice( boolean success);
    }
    
    
   //protected  abstract void setOnSavecolorListener(OnSaveColorListener listener);

  //接口可以实例化对象
    private OnAddDeviceListener adddevicelistener;
    
    //覆写父类抽象方法
    public void SetOnAddchildListener(OnAddDeviceListener listener){
    	adddevicelistener = listener;
    }

	

	
    
   
}
